/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao.mysql;

import dao.TransaksiDetailDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import model.TransaksiDetail;

/**
 *
 * @author Student
 */
public class TransaksiDetailDAOImpl implements TransaksiDetailDAO{

    private Connection conn;
    public TransaksiDetailDAOImpl(Connection conn){
        this.conn = conn;
    }
    
    @Override
    public int save(String transaksiId, TransaksiDetail detail) throws Exception {
        String sql = "INSERT INTO transaksi_detail(transaksi_id,product_id,quantity,price) "
                + "VALUES(?,?,?,?)";
        int out = 0;
        PreparedStatement ps = null;
        try{
            ps = this.conn.prepareStatement(sql);
            ps.setString(1,transaksiId);
            ps.setInt(2,detail.getProduct().getId());
            ps.setInt(3,detail.getQuantity());
            ps.setDouble(4, detail.getPrice());
            out = ps.executeUpdate();
        }catch(Exception ex){
            throw ex;
        }
        return out;        
    }

    @Override
    public List<TransaksiDetail> getByTransaksiId(String transaksiId) throws Exception {
        String sql = "SELECT id,product_id,quantity,price FROM transaksi_detail WHERE "
                + "transaksi_id=?";
        List<TransaksiDetail> details = new ArrayList<TransaksiDetail>();
        PreparedStatement ps = null;
        try{
           ps = this.conn.prepareStatement(sql);
           ps.setString(1, transaksiId);
           ResultSet rs = ps.executeQuery();
           while(rs.next()){
               TransaksiDetail detail = new TransaksiDetail();
               detail.setId(rs.getInt(1));
               detail.setProduct(new ProductDAOImpl(this.conn).getProductById(rs.getInt(2)));
               detail.setQuantity(rs.getInt(3));
               detail.setPrice(rs.getDouble(4));
               details.add(detail);
           }
        }catch(Exception ex){
            throw ex;
        }
        return details;
    }
    
}
